package com.fangcun.service.admin.Impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fangcun.bean.admin.order.request.OrderDeliveredRequest;
import com.fangcun.bean.admin.order.request.OrderRequest;
import com.fangcun.bean.admin.order.response.OrderDetailsResponse;
import com.fangcun.bean.admin.order.response.OrderResponse;
import com.fangcun.bean.sys.PageBean;
import com.fangcun.common.canstant.ErrCode;
import com.fangcun.common.enums.OrderStatusEnum;
import com.fangcun.common.enums.PayCodeEnum;
import com.fangcun.common.exception.ProException;
import com.fangcun.common.exception.ProValiDataException;
import com.fangcun.common.util.PublicMethod;
import com.fangcun.common.util.date.DateUtils;
import com.fangcun.common.util.excel.ExcelUtils;
import com.fangcun.entity.Order;
import com.fangcun.entity.OrderAddress;
import com.fangcun.mapper.OrderAddressMapper;
import com.fangcun.mapper.OrderMapper;
import com.fangcun.service.admin.OrderSerivce;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class OrderSerivceImpl implements OrderSerivce {

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private OrderAddressMapper orderAddressMapper;
	// @Autowired
	// private OrderCardNumberMapper OrderCardNumberMapper;
	// @Autowired
	// private OrderDetailMapper orderDetailMapper;
	// @Autowired
	// private SysPaymentMapper sysPaymentMapper;
	// @Autowired
	// private UserTransactionFlowMapper userTransactionFlowMapper;

	@Override
	public PageInfo<OrderResponse> list(PageBean<OrderRequest> request) throws ProException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		if (!StringUtils.isEmpty(request.getParam().getCreateStartTime())) {
			request.getParam().setCreateStartTime(request.getParam().getCreateStartTime() + " 00:00:00");
		}
		if (!StringUtils.isEmpty(request.getParam().getCreateEndTime())) {
			try {
				request.getParam().setCreateEndTime(DateUtils.DF_SEPARATE.get()
						.format(DateUtils.getAddorSubtractTimes(DateUtils.DF_SEPARATE_YMD.get().parse(request.getParam().getCreateEndTime()), 0, 0, 0, 1, 0, 0)));
			} catch (ParseException e) {
			}
		}
		List<OrderResponse> list = orderMapper.listForAdmin(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		for (OrderResponse r : list) {
			r.setOrderStatusValue(OrderStatusEnum.orderStatusVaule(r.getOrderStatus()));
			r.setOrderSubStatusValue(OrderStatusEnum.orderStatusVaule(r.getOrderSubStatus()));
		}
		return new PageInfo<>(list);
	}

	@Override
	public OrderDetailsResponse details(Long id) throws ProException {
		OrderDetailsResponse details = orderMapper.adminOrderDetail(id);
		if (details == null) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		details.setOrderStatusValue(OrderStatusEnum.orderStatusVaule(details.getOrderStatus()));
		details.setOrderSubStatusValue(OrderStatusEnum.orderStatusVaule(details.getOrderSubStatus()));
		return details;
	}

	/** 改为已发货 **/
	@Override
	public void orderDelivered(OrderDeliveredRequest request) throws ProException {
		if (!StringUtils.isEmpty(request.getRemark()) && request.getRemark().length() > 256) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "备注字数不能超过256个字");
		}
		Order order = orderMapper.selectByPrimaryKey(request.getId());

		// OrderDetail orderDetail = orderDetailMapper.selectByPrimaryKey(order.getId());
		// if (orderDetail.getNumber() != request.getCardNumber().size()) {
		// throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "请输入购买几个商品输入几个卡号");
		// }
		/** 查询 相应的收货人 为了添加 快递 和 运单号 **/
		OrderAddress orderAddress = orderAddressMapper.selectByOrderId(request.getId());
		if (order == null || orderAddress == null) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (request.getDistributorUserId() != null && request.getDistributorUserId() != order.getTeahouseId()) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "该订单无权操作");
		}
		if (OrderStatusEnum.MAIN_ORDER_STATUS_2.getStatus() != order.getOrderStatus()) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "该订单不是已支付，不能发货");
		}
		/** 添加快递公司 和单号 **/
		OrderAddress oradd = new OrderAddress();
		oradd.setId(orderAddress.getId());
		oradd.setExpressCompany(request.getExpressCompany());
		oradd.setExpressNumber(request.getExpressNumber());
		oradd.setDeliveryTime(new Date());
		/****/
		Order update = new Order();
		update.setId(request.getId());
		update.setOrderStatus(OrderStatusEnum.MAIN_ORDER_STATUS_3.getStatus());
		update.setDeliveryTime(new Date());
		update.setRemark(request.getRemark());
		/** 增加 卡号 **/
		// OrderCardNumber add=new OrderCardNumber();
		// int addCardNumber = 0;
		// for (String iterable : request.getCardNumber()) {
		// if(!StringUtils.isEmpty(iterable) && iterable.length() > 26 ) {
		// throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "卡号字数不能超过26位数");
		// }
		// add.setOrderDetailId(request.getId());
		// add.setCardNumber(iterable);
		// addCardNumber = OrderCardNumberMapper.insertSelective(add);
		// }
		int updateAddress = orderAddressMapper.updateByPrimaryKeySelective(oradd);
		int i = orderMapper.updateByPrimaryKeySelective(update);
		// if(addCardNumber <=0) {
		// throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "添加卡号失败");
		// }else
		if (updateAddress <= 0) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "物流公司未获取到");
		} else if (i <= 0) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "发货失败");
		}
	}

	// /**审核失败修改退款单**/
	// @Override
	// @Transactional
	// public void updateApplyFailRefund(Order request) throws ProAffairException {
	// Order old = orderMapper.selectByPrimaryKey(request.getId());
	// if (old == null) {
	// throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
	// }
	// if (OrderStatusEnum.REFUND_ORDER_STATUS_7.getStatus() != old.getOrderSubStatus()) {
	// throw new ProRunTimeException(ErrCode.ORDER_STATUS_UPDATE.getReturnCode(),
	// ErrCode.ORDER_STATUS_UPDATE.getReturnMsg());
	// }
	// request.setOrderSubStatus(OrderStatusEnum.REFUND_ORDER_STATUS_10.getStatus());
	// request.setUpdateTime(null);
	// if (orderMapper.updateByPrimaryKeySelective(request) <= 0) {
	// throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "修改退款订单失败");
	// }
	// }
	// /**申请退货成功**/
	// @Override
	// @Transactional
	// public String updateApplySuccessRefund(Order request, Long distributorId) throws ProAffairException {
	// Order old = orderMapper.selectByPrimaryKey(request.getId());
	// if (old == null) {
	// throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
	// }
	// old.setUpdateTime(null);
	// old.setRemark("");
	// if (OrderStatusEnum.REFUND_ORDER_STATUS_7.getStatus() != old.getOrderSubStatus()) {
	// throw new ProRunTimeException(ErrCode.ORDER_STATUS_UPDATE.getReturnCode(),
	// ErrCode.ORDER_STATUS_UPDATE.getReturnMsg());
	// }
	// OrderDetailsResponse orderDetail = null;
	// try {
	// orderDetail = details(old.getId());
	// } catch (ProException e) {
	// throw new ProRunTimeException(e.getErrorCode(), e.getErrorMsg());
	// }
	// // 如果是已支付 则直接退款
	// if (OrderStatusEnum.MAIN_ORDER_STATUS_2.getStatus() == orderDetail.getOrderStatus()) {
	// return refundPrice(orderDetail, old);
	// }
	// // 如果是已发货，已收货 改为收取快递中
	// if (OrderStatusEnum.MAIN_ORDER_STATUS_3.getStatus() == orderDetail.getOrderStatus()
	// || OrderStatusEnum.MAIN_ORDER_STATUS_4.getStatus() == orderDetail.getOrderStatus()) {
	// old.setOrderSubStatus(OrderStatusEnum.REFUND_ORDER_STATUS_8.getStatus());
	// if (orderMapper.updateByPrimaryKeySelective(old) <= 0) {
	// throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "修改退货信息失败");
	// }
	// return "退回货物过后退款到支付账户";
	// }
	// return null;
	// }
	// /**收到退货快递过后执行退款**/
	// @Override
	// @Transactional
	// public void refundUserPrice(Order request, Long distributorId) throws ProAffairException {
	// Order old = orderMapper.selectByPrimaryKey(request.getId());
	// if (old == null) {
	// throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
	// }
	// old.setUpdateTime(null);
	// old.setRemark("");
	// if (OrderStatusEnum.REFUND_ORDER_STATUS_8.getStatus() != old.getOrderSubStatus()) {
	// throw new ProRunTimeException(ErrCode.ORDER_STATUS_UPDATE.getReturnCode(),
	// ErrCode.ORDER_STATUS_UPDATE.getReturnMsg());
	// }
	// OrderDetailsResponse orderDetail = null;
	// try {
	// orderDetail = details(old.getId());
	// } catch (ProException e) {
	// throw new ProRunTimeException(e.getErrorCode(), e.getErrorMsg());
	// }
	// // 如果是已发货，已收货 改为收取快递中
	// if (OrderStatusEnum.MAIN_ORDER_STATUS_3.getStatus() == orderDetail.getOrderStatus()
	// || OrderStatusEnum.MAIN_ORDER_STATUS_4.getStatus() == orderDetail.getOrderStatus()) {
	// refundPrice(orderDetail, old);
	// }
	// }
	//
	// // 调用第三方退款接口退款
	// private String refundPrice(OrderResponse orderDetail, Order old) throws ProAffairException {
	// SysPayment payment = sysPaymentMapper.selectByPayTypeAndSource(orderDetail.getPayType(),
	// orderDetail.getSource());
	// if (payment == null) {
	// throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), "获取支付信息失败");
	// }
	// if (payment.getPayType() == PayCodeEnum.WECHAT.getType()) {
	// Map<String, String> refundMap = WXPayUtils.wechatRefund(orderDetail, orderDetail, payment);
	// old.setOrderNumber(refundMap.get("transaction_id"));
	// LOG.error("-后台->订单退款-微信->{}", JSONTools.obj2json(refundMap));
	// } else {
	// throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "无匹配的支付信息");
	// }
	// old.setReceivingTime(new Date());
	// old.setOrderSubStatus(OrderStatusEnum.REFUND_ORDER_STATUS_9.getStatus());
	// if (orderMapper.updateByPrimaryKeySelective(old) <= 0) {
	// throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "修改退货信息失败");
	// }
	// // 记录流水
	//// UserTransactionFlow flow = new UserTransactionFlow();
	//// flow.setUserId(orderDetail.getUserId());
	//// flow.setResType(PublicConstant.RES_TYPE_6);
	//// flow.setResId(orderDetail.getId());
	//// flow.setFlowType(PublicConstant.FLOW_TYPE_1);
	//// flow.setPrice(old.getRefundPrice());
	//// flow.setReason("商品退款");
	//// if (userTransactionFlowMapper.insertSelective(flow) <= 0) {
	//// throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "记录流水失败");
	//// }
	// return "已经退款到用户支付账户";
	// }

	@Override
	public String down(OrderRequest request) throws ProException {
		if (!StringUtils.isEmpty(request.getCreateEndTime())) {
			try {
				request.setCreateEndTime(
						DateUtils.DF_SEPARATE.get().format(DateUtils.getAddorSubtractTimes(DateUtils.DF_SEPARATE_YMD.get().parse(request.getCreateEndTime()), 0, 0, 0, 1, 0, 0)));
			} catch (ParseException e) {
			}
		}
		List<OrderDetailsResponse> list = orderMapper.listForExcel(request);
		if (list == null || list.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}

		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		Map<String, String> title = new HashMap<String, String>();
		title.put("name_0", "订单号");
		title.put("name_1", "商品名称");
		title.put("name_2", "商品规格");
		title.put("name_3", "购买份数");
		title.put("name_4", "订单状态");
		title.put("name_5", "下单日期");
		title.put("name_6", "支付类型");
		title.put("name_7", "支付日期");
		title.put("name_8", "支付金额");
		title.put("name_9", "联系人");
		title.put("name_10", "联系电话");
		title.put("name_11", "收货地址");
		title.put("name_12", "推广ID");
		data.add(title);

		BigDecimal totalPrice = BigDecimal.valueOf(0);
		for (OrderDetailsResponse r : list) {
			r.setOrderStatusValue(OrderStatusEnum.orderStatusVaule(r.getOrderStatus()));
			totalPrice = totalPrice.add(r.getActualPrice());

			for (int i = 0; i < r.getGoodsList().size(); i++) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("name_0", r.getOrderNumber());
				map.put("name_1", r.getGoodsList().get(i).getTitle());
				map.put("name_2", r.getGoodsList().get(i).getSpecifications());
				map.put("name_3", r.getGoodsList().get(i).getNumber().toString());
				if (i == 0) {
					map.put("name_4", r.getOrderStatusValue());
					map.put("name_5", DateUtils.DF_SEPARATE.get().format(r.getCreateTime()));
					map.put("name_6", PayCodeEnum.payTypeCode(r.getPayType()));
					map.put("name_7", StringUtils.isEmpty(r.getPayTime()) ? "" : DateUtils.DF_SEPARATE.get().format(r.getPayTime()));
					map.put("name_8", r.getActualPrice().toString());
					map.put("name_9", r.getReceivingName());
					map.put("name_10", r.getPhone());
					map.put("name_11", r.getAddress() != null ? r.getAddress().getAddress() : "");
					map.put("name_12", r.getRecommendUserId() != null ? r.getRecommendUserId().toString() : "");
				} else {
					map.put("name_4", "");
					map.put("name_5", "");
					map.put("name_6", "");
					map.put("name_7", "");
					map.put("name_8", "");
					map.put("name_9", "");
					map.put("name_10", "");
					map.put("name_11", "");
					map.put("name_12", "");
				}
				data.add(map);
			}
		}

		Map<String, String> map = new HashMap<String, String>();
		map.put("name_0", "");
		map.put("name_1", "");
		map.put("name_2", "");
		map.put("name_3", "");
		map.put("name_4", "");
		map.put("name_5", "");
		map.put("name_6", "");
		map.put("name_7", "");
		map.put("name_8", "订单总金额：" + totalPrice);
		map.put("name_9", "");
		map.put("name_10", "");
		map.put("name_11", "");
		map.put("name_12", "总订单数量：" + list.size());
		data.add(map);

		String excelPath = PublicMethod.getCachePath() + "order_" + DateUtils.DF_CLOSED.get().format(new Date()) + ".xlsx";
		ExcelUtils.writeExcel(data, excelPath);
		return excelPath;
	}

}
